class MyPromise{
	constructor(executor) {
		let self = this;
	    this.state="pedding";
		this.value = null
		this.reason = null;
		this.onResolvedCallbacks = [];
		this.onRejectedCallbacks = [];
		let resolve = function(value){
			if (value instanceof Promise) {
			      return value.then(resolve, reject)
			    }
			setTimeout(function(){
				if(self.state == "pedding"){
					self.state = "resolve";
					self.value = value;
					self.onResolvedCallbacks.forEach(fn=>fn(self.value));
				}
			},0);
		};
		let reject = function(reason){
			setTimeout(function(){
				if(self.state == "pedding"){
					self.state = "reject";
					self.reason = reason;
					self.onRejectedCallbacks.forEach(fn=>fn(self.reason));
				}
			})
		};
		try{
			executor(resolve,reject);
		}catch(e){
			//TODO handle the exception
			reject(e);
		}
	}
	resolvePromise(promise2,x,resolve,reject){
		if(x == promise2){
			return reject(new Error("不能重复引用"))
		}
		if(x instanceof MyPromise){
			if(x.state == "pending"){
				x.then(function(v){
					resolvePromise(promise2,v,resolve,reject);
				},reject)
			}else{
				try{
					x.then(resolve,reject);
				}catch(err){
					reject(err)
				}
			}
			return;
		}
		if(x != null &&(typeof x == "function" || typeof x == "object")){
			let then;
			isCall = false;
			try{
				then = x.then;
				if(typeof x == "function"){
					then.call(x,function rs(y){
						if(isCall){
							return;
						}
						isCall = true;
						return resolvePromise(promise2,v,resolve,reject);
					},function rj(r){
						if(isCall){
							return;
						}
						isCall = true;
					})
				}
			}catch(err){
				reject(err);
			}
		}else{
			resolve(x);
		}
	}
	then(onFufilled,onRejected){
		let promise2 = null; //需要返回的promise
		if(this.state == "resolve"){
			promise2 = new MyPromise((resolve,reject)=>{
				setTimeout(function(){
					let x = onFufilled(this.value);//then函数中的参数 x即为函数调用完之后返回的数据
					this.resolvePromise(promise2,x,resolve,reject);
				},0)
			});
		}
		if(this.state == "reject"){
			promise2 = new MyPromise((resolve,reject)=>{
				setTimeout(function(){
					let x = onRejected(this.value);//then函数中的参数 x即为函数调用完之后返回的数据
					this.resolvePromise(promise2,x,resolve,reject);
				})
			},0);
		}
		if(this.state == "pedding"){
			this.onResolvedCallbacks.push((value)=>{
				promise2 = new MyPromise((resolve,reject)=>{
					let x = onFufilled(value);//then函数中的参数 x即为函数调用完之后返回的数据
					this.resolvePromise(promise2,x,resolve,reject);
				})
			})
			this.onRejectedCallbacks.push((value)=>{
				promise2 = new MyPromise((resolve,reject)=>{
					let x = onRejected(value);//then函数中的参数 x即为函数调用完之后返回的数据
					this.resolvePromise(promise2,x,resolve,reject);
				})
			})
		}
	}
}

let p = new MyPromise(function(resolve,reject){
	resolve("成功");
});
p.then((val)=>{
	console.log(val)
	return new MyPromise((resolve,reject)=>{
		resolve("err")
	})
},(err)=>{});

p.then(function(v){
	console.log(2+v)
},function(err){
	console.log(err)
})


